<script setup>
import {ref} from 'vue'
import {useTokenStore} from "@/stores/token";
import useUserInfoStore from "@/stores/userInfo";
import {useRouter} from "vue-router";
import {customerRepasswordService} from "@/apis/customer";
import {ElMessage} from "element-plus";
const passwordInfo = ref({
    old_pwd: '',
    new_pwd: '',
    re_pwd: ''
})
const tokenStore = useTokenStore()
const userInfoStore = useUserInfoStore()
const router = useRouter()

// 表单校验
const validatePass = (rule, value, callback) => {
    if (value === '') {
        callback(new Error('确认密码不能为空'))
    } else if (value !== passwordInfo.value.new_pwd) {
        callback(new Error('两次输入密码不一致!'))
    } else {
        callback()
    }
}

const rules = {
    old_pwd: [
        {required: true, message: '请输入密码', trigger: 'blur'},
        {min: 5, max: 16, message: '密码长度5-16位', trigger: 'blur'}
    ],
    new_pwd: [
        {required: true, message: '请输入密码', trigger: 'blur'},
        {min: 5, max: 16, message: '密码长度5-16位', trigger: 'blur'}
    ],
    re_pwd: [
        {validator: validatePass, trigger: 'blur'},
    ],
}

// 修改密码
const customerRepassword = async () => {
    let result = await customerRepasswordService(passwordInfo.value)
    tokenStore.removeToken();
    userInfoStore.removeInfo();
    router.push('/login');
    ElMessage.success(result.message ? result.message : '修改成功');
}
</script>

<template>
    <el-card class="page-container">
        <template #header>
            <div><el-button @click="$router.push('/')" style="font-size: 12px;"><el-icon style="margin-right: 10px"><ArrowLeft /></el-icon>回到首页</el-button></div>
            <div class="header">
                <span>修改密码</span>
            </div>
        </template>
        <el-row>
            <el-col :span="12">
                <el-form  label-width="120px" size="large" :model="passwordInfo" :rules="rules">
                    <el-form-item label="旧密码" prop="old_pwd">
                        <el-input type="password" v-model="passwordInfo.old_pwd"></el-input>
                    </el-form-item>
                    <el-form-item label="新密码" prop="new_pwd">
                        <el-input type="password" name="newPassword" v-model="passwordInfo.new_pwd"></el-input>
                    </el-form-item>
                    <el-form-item label="确认新密码" prop="re_pwd">
                        <el-input type="password" name="rePassword" v-model="passwordInfo.re_pwd"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="customerRepassword">提交修改</el-button>
                    </el-form-item>
                </el-form>
            </el-col>
        </el-row>
    </el-card>
</template>

<style scoped>

.header {
    font-size: 20px;
    font-weight: bold;
    margin-top: 10px;
}
</style>